package com.teamwhole.modules.mobile.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.FormParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Component;

import com.google.common.collect.Maps;
import com.teamwhole.common.model.ResultInfo;

@Component
@Path("/mobile/login")
@Produces("application/json;charset=utf-8")
public class MobileLoginResource {
	
	@Context
	private HttpServletRequest request;
	
	@GET
	@Consumes("application/json;charset=utf-8")
	public Object login() {
		ResultInfo info = new ResultInfo();
		info.setErrcode(-1);
		info.setErrmsg("登陆超时.");
		return info;
	}
	
	@POST
	@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
	public Object login(@FormParam("username") String username,@FormParam("password") String password) {
		//String username = request.getParameter("username");
        //String password = request.getParameter("password");
		Subject subject = SecurityUtils.getSubject();
        AuthenticationToken token = new UsernamePasswordToken(username, password);
        Map<String, Object> map = Maps.newHashMap();
        try {
            subject.login(token);
            map.put("errcode", 0);
            map.put("errmsg", "ok");
            map.put("token", subject.getSession().getId().toString());
        } catch (AuthenticationException e) {
        	map.put("errcode", 1);
            map.put("errmsg", "用户名或密码错误.");
        }
        return map;
	}
	
}
